<template>
  <div class="page-container">
    <div class="info-container">
      <div class="info-container_header">
        <div class="title">{{ title }}</div>
      </div>
      <div class="info-container_body">
        <el-form ref="refFrom" label-position="top" :model="form.model" class="demo">
          <div class="form-section">
            <div class="form-section_title">基础信息</div>
            <AgelFormGrid :items="form.baseItems" :span="6" :gutter="16">
              <template #slot-vendor>
                <vendor-select v-model="form.model.vendorId" @change="vendorChange"></vendor-select>
              </template>
            </AgelFormGrid>
          </div>
          <div class="form-section">
            <div class="form-section_title">分佣信息</div>
            <el-form-item class="w-700" prop="bonus">
              <ContractBonu ref="contractBonuRef" v-model="form.model.bonus"></ContractBonu>
              <ContractIncentive ref="contractIncentiveRef" v-model="form.model.incentives"></ContractIncentive>
            </el-form-item>
          </div>
          <div class="form-section">
            <div class="form-section_title">合同扫描件</div>
            <el-form-item prop="attachments">
              <image-upload v-model="form.model.attachments" :limit="100"></image-upload>
            </el-form-item>
          </div>
        </el-form>
      </div>
      <div class="info-container_footer">
        <el-button @click="handleCancel">取消</el-button>
        <el-button type="primary" @click="handleSubmit">确定</el-button>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { addContract, updateContract, getContract } from '@/api/operation/contract/index';
import { BizContractVo, defaultModel } from '@/api/operation/contract/types';
import RegionSelect from '@/components/RegionSelect/index.vue';
import ImageUpload from '../common/ImageUpload/index.vue';
import VendorSelect from '@/views/common/vendor-select/index.vue';
import ContractBonu from '../common/contract-bonu/index.vue';
import ContractIncentive from '../common/contract-incentive/index.vue';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { settle_period_type } = toRefs<any>(proxy?.useDict('settle_period_type'));

const route = useRoute();
const orderId = toRef<string | null>(route.query.id as string);
const title = computed(() => {
  return orderId.value ? '编辑合同' : '新增合同';
});

const form = reactive({
  model: defaultModel(),
  baseItems: [
    { prop: 'contractNo', label: '合同编号', span: 6, required: true },
    { prop: 'vendorId', label: '酒店名称', slot: 'slot-vendor', required: true },
    { prop: 'regionCode', label: '省市区', slot: RegionSelect, required: true },
    { prop: 'vendorUser', label: '联系人', required: true },
    { prop: 'vendorPhone', label: '联系人电话', required: true },
    { prop: 'signUser', label: '销售负责人', required: true },
    {
      prop: 'validRange',
      label: '运营期起止',
      required: true,
      slot: 'el-date-picker',
      attrs: { startPlaceholder: '开始日期', endPlaceholder: '结束日期', type: 'daterange', valueFormat: 'YYYY-MM-DD HH:mm:ss' }
    },
    {
      prop: 'signTime',
      label: '签订日期',
      required: true,
      slot: 'el-date-picker',
      attrs: { class: 'full-w', placeholder: '请选择', type: 'date', valueFormat: 'YYYY-MM-DD HH:mm:ss' }
    },
    {
      prop: 'settlePeriodType',
      label: '结算周期',
      required: true,
      slot: 'agel-select',
      attrs: {
        options: settle_period_type
      }
    },
    { prop: 'autoSettleEnabled', label: '是否启用自动结算', slot: 'el-switch', attrs: { activeValue: '1', inactiveValue: '0' } }
  ]
});
const loading = ref(false);
const refFrom = ref<ElFormInstance>();
const contractBonuRef = ref();
// 酒店change事件
const vendorChange = (val: any) => {
  form.model.regionCode = val.regionCode;
  form.model.vendorUser = val.contactPerson;
  form.model.vendorPhone = val.phone;
};
/** 取消 */
const handleCancel = () => {
  // proxy?.$tab.closeOpenPage()
  proxy?.$tab.closePage();
};
/** 确认 */
const handleSubmit = async () => {
  if (!refFrom.value) return;
  refFrom.value.validate(async (valid, fields) => {
    if (valid) {
      let pass = await contractBonuRef.value?.validate();
      if (pass) {
        requestAdd();
      } else {
        proxy?.$modal.msgWarning('请填写正确的分佣信息');
      }
    } else {
      console.log('error submit!', fields);
    }
  });
};
const getInfo = async (id: string) => {
  loading.value = true;
  let res = await getContract(id);
  loading.value = false;
  if (res.code == 200) {
    let model=res.data;
    model.validRange=[model.validFrom,model.validTo];
    form.model = model;
  } else {
    proxy?.$modal.msgError(res.msg || '创建失败！');
  }
};
const requestAdd = async () => {
  let serviceHandle = orderId.value ? updateContract : addContract;

  // 处理数据
  form.model.validFrom = form.model.validRange[0] || '';
  form.model.validTo = form.model.validRange[1] || '';

  loading.value = true;
  let data = JSON.parse(JSON.stringify(form.model));
  data.incentives.forEach((item) => {
    item.amountFloor *= 100;
    item.amountRoof *= 100;
  });
  let res = await serviceHandle(data as BizContractVo);
  loading.value = false;
  if (res.code == 200) {
    proxy?.$modal.msgSuccess('操作成功！');
    proxy?.$tab.closeOpenPage('/operation/operContract');
  } else {
    proxy?.$modal.msgError(res.msg || '操作失败！');
  }
};

if (orderId.value) {
  getInfo(orderId.value);
}
onMounted(() => {});
</script>
